from django.utils import timezone
from urllib.parse import urljoin
from django.shortcuts import render, redirect
from django.contrib.auth import logout
from django.http.response import JsonResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth.hashers import check_password
from django.urls import reverse
from django.views.decorators.clickjacking import xframe_options_sameorigin
from django.views.decorators.csrf import csrf_exempt
from index.models import *


# Create your views here.

def loginView(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        try:
            u = User.objects.get(username=username)
            if not check_password(password, u.password):
                return JsonResponse({
                    "status": 2,
                    "msg": "密码错误"
                })
            else:
                user = authenticate(username=username, password=password)
                if user:
                    login(request, user)
                    return JsonResponse({
                        "status": 1,
                        "msg": "登录成功",
                        "name": user.get_username()
                    })
        except User.DoesNotExist:
            u = User.objects.create_user(**{
                "username": username,
                "password": password,
                "last_login": timezone.now()
            })
            # u.first_name = username[0]
            # u.last_name = username[1:]
            # u.email = f"{username}@qq.com"
            u.save()
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                return JsonResponse({
                    "status": 1,
                    "msg": "登录成功",
                    "name": user.get_username()
                })
    return render(request, "index/login.html")


def registerView(request):
    if request.method == "POST":
        username = request.POST.get("un")
        password = request.POST.get("pw")
        print(User.objects.filter(username=username))
        if not User.objects.filter(username=username):
            User.objects.create_user(username=username, password=password)
            return JsonResponse({
                "status": 1,
                "msg": "注册成功"
            })
        else:
            return JsonResponse({
                "status": 2,
                "msg": "用户名存在"
            })
    return render(request, "index/register.html")


# @login_required()
def indexView(request):
    return render(request, "index/index.html")


# def logOutView(request):
#     logout(request)  # 注销用户
#     return redirect(reverse("index:login"))  # 重定向到登录页面

@xframe_options_sameorigin
@csrf_exempt
def statisticsView(request):
    # 项目综合模块
    return render(request, "index/statistics.html")


# @xframe_options_sameorigin
# @csrf_exempt
# def createProjectView(request):
#     # 创建项目
#     if request.method == "POST":
#         if ProjectModel.objects.filter(name=request.POST.get("pname")):
#             return JsonResponse({
#                 "status": 2,
#                 "msg": "项目已存在"
#             })
#         ProjectModel.objects.create(**{
#             "name": request.POST.get("pname"),
#             "createor": request.user
#         })
#         p_obj = ProjectModel.objects.get(name=request.POST.get("pname"))
#         object = [
#             TestTypeModel(name="UI测试用例", project=p_obj,
#                           createor=request.user, type=1),
#             TestTypeModel(name="接口测试用例", project=p_obj,
#                           createor=request.user, type=4),
#             # TestTypeModel(name="UI自动化场景测试用例", project=p_obj, createor=request.user, type=2),
#             # TestTypeModel(name="接口自动化场景测试用例", project=p_obj, createor=request.user, type=5),
#             TestTypeModel(name="UI自动化测试结果", project=p_obj,
#                           createor=request.user, type=3),
#             TestTypeModel(name="接口自动化测试结果", project=p_obj,
#                           createor=request.user, type=6)
#         ]
#         TestTypeModel.objects.bulk_create(object)
#         # 创建项目的接口、UI文件夹
#         pro_test_dir = urljoin(pro_path, f"tests/test{p_obj.name}/")
#         print(f"项目测试文件夹路径：{pro_test_dir}")
#         if not os.path.exists(pro_test_dir):
#             os.makedirs(pro_test_dir)
#         pro_test_inf_dir = urljoin(pro_test_dir, "testJK")
#         if not os.path.exists(pro_test_inf_dir):
#             os.makedirs(pro_test_inf_dir)
#         pro_test_ui_dir = urljoin(pro_test_dir, "autoUI")
#         if not os.path.exists(pro_test_ui_dir):
#             os.makedirs(pro_test_ui_dir)
#         return JsonResponse({
#             "status": 1,
#             "msg": "创建项目成功"
#         })
